import time
import sys


sys.path.append("../")  # noqa
from bson import ObjectId
from pymongo import UpdateOne, MongoClient
from collections import defaultdict

from config import client
from config import col_alumni, col_activity, col_institution, col_register, col_activity_institution
from task_utils.task_activity_span_year import query_year
from task_utils.task_institution_overview import institution_query

col_inst = col_institution
activity_col = col_activity
institution_col = col_institution
activity_register_col = col_register
col_person = col_alumni


def task_accumulate_metric(institution: str, sync=False):
    """累计组织活动 累计联系人次 累计的人数"""
    query = institution_query(inst_id=institution)
    query["is_deleted"] = {"$ne": True}

    act_ids = activity_col.find(query).distinct("_id")

    contact_docs = activity_register_col.find(
        {"activity_id": {"$in": act_ids}, "is_attended": True}, {"person_id": 1, "_id": 0}
    )
    contact_ids = [p.get("person_id") for p in contact_docs]

    acc_act = len(act_ids)
    acc_join = len(contact_ids)  # 累计联系人次
    acc_alumni = len(set(contact_ids))  # 累计的人数

    contact_institution_docs = col_activity_institution.find(
        {"activity_id": {"$in": act_ids}, "is_attended": True}, {"institution_id": 1, "_id": 0}
    )

    contact_institution_ids = [p.get("institution_id") for p in contact_institution_docs]

    acc_institution = len(set(contact_institution_ids))  # 累计的组织数

    if sync:
        institution_col.update_one(
            {"_id": ObjectId(institution)},
            {"$set": {"served_people_num": acc_act, "acc_activity": acc_act,
                      "acc_join": acc_join, "acc_alumni": acc_alumni, "acc_institution": acc_institution}},
        )
    return acc_act, acc_alumni, acc_join, acc_institution


if __name__ == '__main__':
    for inst in col_institution.find({"is_deleted": {"$ne": True}, "level": {"$in": [0, 1]}}):
        print(task_accumulate_metric("62b945cd9aebef53937fecc4", sync=True))
        break
